import uuid

from rest_framework.views import APIView
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.decorators import action
from rest_framework.response import Response

from rest_framework.viewsets import ModelViewSet

from app01 import models
from app01.app_auth import MyAuthentication, UserPermission
from app01.ser import BookSerializer


# Create your views here.


# 过滤组件的使用
class BookView(ModelViewSet):
    queryset = models.Book.objects.all()
    serializer_class = BookSerializer
    authentication_classes = []
    permission_classes = []
    filter_fields = ('name', 'price', 'publish')  # 想要哪个字段过滤

    @action(methods=['get'], detail=True)
    def get_1(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(instance=book)
        return Response({'status': 100, 'msg': '查询成功', 'data': ser.data})

    @action(methods=['get'], detail=False)
    def get_all(self, request):
        book_list = self.get_queryset()
        ser = self.get_serializer(instance=book_list, many=True)
        return Response({'status': 100, 'msg': '查询成功', 'data': ser.data})


class LoginView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = models.User.objects.filter(username=username, password=password).first()
        if user:
            token = uuid.uuid4()
            print(token)
            models.UserToken.objects.update_or_create(defaults={'token': token}, user=user)
            return Response({'status': 100, 'msg': '登录成功', 'token': token})
        else:
            return Response({'status': 101, 'msg': '用户名或密码错误'})


# 超级用户才能访问
class TestView(APIView):
    authentication_classes = [MyAuthentication, ]
    permission_classes = [UserPermission, ]
    # throttle_classes = []

    def get(self, request):
        return Response('测试')


class TestView2(APIView):
    # authentication_classes = [MyAuthentication, ]
    permission_classes = []
    # throttle_classes = []

    def get(self, request):
        return Response('测试wwwww')


# 演示内置权限，只有超级管理员才能查看
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication


class TestView3(APIView):
    # rest_framework.request.WrappedAttributeError: 'IsAdminUser' object has no attribute 'authenticate'
    # 权限与认证必须一起用
    authentication_classes = [SessionAuthentication, ]
    permission_classes = [IsAdminUser, ]
    # throttle_classes = []

    def get(self, request):
        return Response('admin')


# 频率限制, test4 演示全局未登录用户访问频次
from rest_framework.throttling import AnonRateThrottle


class TestView4(APIView):
    authentication_classes = []
    permission_classes = []
    throttle_classes = []

    def get(self, request, *args, **kwargs):
        return Response('全局未登录')


# test5 演示 局部未登录用户的访问频次
class TestView5(APIView):
    authentication_classes = []
    permission_classes = []
    throttle_classes = [AnonRateThrottle, ]

    def get(self, request, *args, **kwargs):
        # 演示异常处理
        1 / 0
        return Response('局部未登录')


# test6 演示全局 登录用户访问频次
class TestView6(APIView):
    authentication_classes = [SessionAuthentication, ]
    permission_classes = []

    def get(self, request, *args, **kwargs):
        return Response('全局登录用户频次')


from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter


# 排序组件的使用
class Book2View(ListAPIView):
    queryset = models.Book.objects.all()
    serializer_class = BookSerializer
    authentication_classes = []
    permission_classes = []
    filter_backends = [OrderingFilter, DjangoFilterBackend]
    ordering_fields = ('id', 'price')  # 定义排序的字段


# 全局异常处理


from app01.app_auth import APIResponse
# 自定义返回对象
class TestView7(APIView):
    authentication_classes = []
    permission_classes = []
    def get(self, request, *args, **kwargs):
        # return APIResponse(code=100, data={'name': 'AK'}, token='afsasfd', url='http://121.196.175.94', status=100)
        return APIResponse(code=101, data={'name': 'AK'}, status=200, token='afsasfd', url='http://121.196.175.94', msg='请求成功')